package com.wardrobe.soa.utils;

import com.wardrobe.handler.CodeHelper;
import com.wardrobe.soa.common.WeChatConsant;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.context.ApplicationContext;

import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by m1304 on 2018/8/3.
 */
public class CommonUtil {

    public static String getRandomFromList(List<String> source){
        Random random = new Random();
        int n = random.nextInt(source.size());
        return source.get(n);
    }

    public static String formatPrice(String prefix, long price){
        DecimalFormat df = new DecimalFormat("###,###.00");
        if(price == 0){
            return prefix + "0.00";
        }
        return prefix + df.format(new BigDecimal(price).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP).longValue());
    }

    public static String formatDate(long time){
        SimpleDateFormat format = new SimpleDateFormat(DateConsant.FORMAT_PATTERN_YMDHMS1);
        return format.format(new Date(time));
    }

    public static long getGoodsSalesVolume(long now, String createTime) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(DateConsant.FORMAT_PATTERN_YMDHMS1);
        Date date = format.parse(createTime);
        return ((now - date.getTime())/DateConsant.ONE_DAY_MILLISECOND) * ((int)(Math.random()*900)+100);
    }

    public static String getSignValue(TreeMap<String,Object> sortedParams) throws Exception {
        StringBuilder subd = new StringBuilder();
        for (String key : sortedParams.keySet()) {
            subd.append(key).append("=").append(sortedParams.get(key)).append("&");
        }
        subd.append("key=").append(WeChatConsant.wechatKey);
        String s = CodeHelper.encodePwdForMd5(subd.toString());
        return s.toUpperCase();
    }

    public static String formatUnifiedorderParam(TreeMap<String,Object> sortParams,String sign){
        StringBuilder res = new StringBuilder("<xml>");
        for(String str : sortParams.keySet()){
            res.append("<").append(str).append(">")
                    .append(sortParams.get(str))
                    .append("</").append(str).append(">");
        }
        res.append("<sign>").append(sign).append("</sign>");
        res.append("</xml>");
        return res.toString();
    }

    public static Map<String ,Object> getXmlValue(String xml) {
        SAXReader saxReader = new SAXReader();
        Document document = null;
        Map<String, Object> nodemap = new HashMap<>();
        Reader reader = null;
        try {
            reader = new StringReader(xml);
            document = saxReader.read(reader);
            Element root = document.getRootElement();
            for (Iterator it = root.elementIterator(); it.hasNext(); ) {
                Element e = (Element) it.next();
                nodemap.put(e.getName(), e.getStringValue());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return nodemap;
    }

    public static String read(InputStream is){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[512];
            while((len = is.read(buffer)) != -1){
                baos.write(buffer, 0, len);
            }
            return new String(baos.toByteArray(), 0, baos.size(), "utf-8");
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

    public static Double getBetweenHours(long begintime,long endtime){
        double hours =(double)(endtime-begintime)/3600/1000;
        return hours;
    }

    public static String getRealmNameUrl(){
        ApplicationContext context = SpringContextUtil.getApplicationContext();
//        String property = context.getEnvironment().getProperty("server.port");
        return CommonConsant.appUrl;
    }

    public static String getProperties(String key){
        ApplicationContext context = SpringContextUtil.getApplicationContext();
        String property = context.getEnvironment().getProperty(key);
        return property;
    }

    public static byte[] toByteArray (Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray ();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }

}
